﻿using System;
using System.Collections.Generic;
using System.Transactions;
using Bingosoft.Data;
using Bingosoft.Modules.SecurityConsole.Common.Config;
using Bingosoft.Security;
using HHMMS.Core.Model;
using HHMMS.Core;

namespace Bingosoft.Modules.SecurityConsole.User
{
    public class UserService
    {
        private readonly Dao dao = Dao.Get();

        /// <summary>
        /// 启用用户账号
        /// </summary>
        /// <param name="userIds">用户Id的集合</param>
        public void EnableAccount(String[] userIds)
        {
            ChangeAccountStatus(userIds, Constants.USER_STATUS_ENABLED);
        }

        /// <summary>
        /// 停用用户账号
        /// </summary>
        /// <param name="userIds">用户Id的集合</param>
        public void DisableAccount(string[] userIds)
        {
            ChangeAccountStatus(userIds, Constants.USER_STATUS_DISABLED);
        }

        private void ChangeAccountStatus(String[] userIds, String accountStatus)
        {
            if (null != userIds && userIds.Length > 0)
            {
                using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
                {
                    IDictionary<string, object> parameters = new Dictionary<string, object> { { "status", accountStatus } };
                    foreach (String userId in userIds)
                    {
                        parameters["userId"] = userId;
                        dao.ExecuteNonQuery("user.changeStatus", parameters);
                    }
                    transactionScope.Complete();
                }
            }
        }

        /// <summary>
        /// 批量删除用户
        /// </summary>
        /// <param name="userIds">用户id数组</param>
        public void DeleteUsers(string[] userIds)
        {
            if (null != userIds && userIds.Length > 0)
            {
                using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
                {
                    IDictionary<string, object> parameters = new Dictionary<string, object>();
                    foreach (string userId in userIds)
                    {
                        parameters["UserId"] = userId;
                        dao.ExecuteNonQuery("user.delete.user.privilege", parameters);
                        dao.ExecuteNonQuery("user.delete.user.role", parameters);
                        dao.ExecuteNonQuery("user.delete.user", parameters);
                    }
                    transactionScope.Complete();
                }
            }
        }

        /// <summary>
        /// 批量删除用户对应的角色
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="roleIds">角色Id集合</param>
        /// <returns></returns>
        public Boolean DeleteRolesFromUser(string userId, string[] roleIds)
        {
            if (null == roleIds || roleIds.Length == 0 || string.IsNullOrEmpty(userId))
            {
                return false;
            }

            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
            {
                foreach (string roleId in roleIds)
                {
                    IDictionary<string, object> parameters = new Dictionary<string, object>
                                                                 {
                                                                     {"UserId", userId},
                                                                     {"RoleId", roleId}
                                                                 };
                    dao.ExecuteNonQuery("user.delete.one.role.of.user", parameters);
                }
                transactionScope.Complete();
                return true;
            }
        }

        /// <summary>
        /// 批量增加用户对应的多个角色
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="roleIds">角色Id集合</param>
        /// <returns></returns>
        public Boolean AddRolesForUser(string userId, string[] roleIds)
        {
            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
            {
                foreach (String roleId in roleIds)
                {
                    if (!string.IsNullOrEmpty(roleId))
                    {
                        IDictionary<string, object> parameters = new Dictionary<string, object> { { "userId", userId }, { "roleId", roleId } };
                        dao.ExecuteNonQuery("user.addUserRole", parameters);
                    }
                }
                transactionScope.Complete();
                return true;
            }
        }

        /// <summary>
        /// 删除特定用户
        /// </summary>
        /// <param name="userId">用户Id</param>
        public void DeleteUser(string userId)
        {
            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
            {
                IDictionary<string, object> parameters = new Dictionary<string, object> { { "UserId", userId } };
                dao.ExecuteNonQuery("user.deleteUserRoles", parameters);
                dao.ExecuteNonQuery("user.deleteUser", parameters);
                transactionScope.Complete();
            }
        }

        /// <summary>
        /// 保存用户信息
        /// </summary>
        /// <param name="userInfo">用户信息</param>
        public void SaveOrUpdateUser(UserInfo userInfo)
        {
            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
            {
                if (string.IsNullOrEmpty(userInfo.Id))
                {
                    userInfo.Id = Guid.NewGuid().ToString();
                    if (string.IsNullOrEmpty(userInfo.OrgId))
                    {
                        userInfo.OrgId = null;
                    }

                    userInfo.Status = Constants.USER_STATUS_ENABLED;
                    //userInfo.Type = Constants.ACCOUNT_TYPE_LOCAL;


                    userInfo.Password = SecurityContext.Provider.EncryptPassword(userInfo.Password);
                    dao.ExecuteNonQuery("user.insertUserInfo", userInfo);
                }
                else
                {
                    dao.ExecuteNonQuery("user.updateUserInfo", userInfo);
                }
                transactionScope.Complete();
            }
        }

        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="encodedPassword">新密码</param>
        public void ResetUserPassword(string userId, string encodedPassword)
        {
            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
            {
                IDictionary<string, object> parameters = new Dictionary<string, object>
                                                         {
                                                             {
                                                                 "Password",
                                                                 SecurityContext.Provider.EncryptPassword(
                                                                     encodedPassword)
                                                                 },
                                                             {"Id", userId}
                                                         };
                dao.ExecuteNonQuery("user.resetPassword", parameters);
                transactionScope.Complete();
            }
        }

        /// <summary>
        /// 检查登录帐号的唯一性
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public Boolean CheckUniqueAccount(string account)
        {
            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
            {
                IDictionary<string, object> parameters = new Dictionary<string, object> { { "account", account } };
                Boolean isUnique = dao.QueryScalar<int>("user.check_account", parameters) > 0;
                transactionScope.Complete();
                return isUnique;
            }
        }

        /// <summary>
        /// 获取组织机构名称
        /// </summary>
        /// <param name="orgId">组织机构Id</param>
        /// <returns></returns>
        public String GetOrgName(String orgId)
        {
            string orgName = String.Empty;
            if (!string.IsNullOrEmpty(orgId))
            {
                using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress))
                {
                    IDictionary<string, object> parameters = new Dictionary<string, object> { { "OrgId", orgId } };
                    orgName = dao.QueryScalar<string>("user.getOrgName", parameters);
                    transactionScope.Complete();
                }
            }
            return orgName;
        }
        /// <summary>
        /// 批量删除用户对应的流程角色
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="roleIds">角色Id集合</param>
        /// <returns></returns>
        public Boolean DeleteWfRolesFromUser(string userId, string[] wfRoleIds)
        {
            if (null == wfRoleIds || wfRoleIds.Length == 0 || string.IsNullOrEmpty(userId))
            {
                return false;
            }

            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
            {
                foreach (string wfRoleId in wfRoleIds)
                {
                    IDictionary<string, object> paramWfu = new Dictionary<string, object>
                                                                 {
                                                                     {"UserId", userId},
                                                                     {"WfRoleId", wfRoleId}
                                                                 };
                    dao.ExecuteNonQuery("user.delete.one.wfuRole.of.user", paramWfu);
                }
                transactionScope.Complete();
                return true;
            }
        }
        /// <summary>
        /// 为用户在某个部门批量添加流程角色
        /// 创建人：谢棉发 2011-06-10 14:30
        /// </summary>
        public void AddWfUserOrgRoles(string userId, string orgId, string[] roleIdArr)
        {
            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
            {
                IDictionary<string, object> param1 = new Dictionary<string, object>() { { "OrgId", orgId } };
                IDictionary<string, object> param2 = new Dictionary<string, object>() { { "UserId", userId } };
                Guid wfRoleId = Guid.Empty;
                foreach (string roleId in roleIdArr)
                {

                    param1["RoleId"] = roleId;
                    wfRoleId = dao.QueryScalar<Guid>("role.existWfRole", param1);
                    if (wfRoleId == Guid.Empty)
                    {
                        wfRoleId = Guid.NewGuid();
                        param1["Id"] = wfRoleId;
                        param2["WfRoleId"] = wfRoleId;
                        dao.ExecuteNonQuery("role.insertWfRole", param1);
                        dao.ExecuteNonQuery("role.insertWfuRole", param2);

                    }
                    else
                    {
                        param2["WfRoleId"] = wfRoleId;
                        dao.ExecuteNonQuery("role.insertWfuRole", param2);
                    }
                }
                transactionScope.Complete();
            }
        }
        /// <summary>
        /// 为用户在某个部门批量添加角色
        /// 创建人：谢棉发 2011-06-10 14:30
        /// </summary>
        /// <param name="roleId"></param>
        /// <param name="userIds"></param>
        public void AddUserOrgRoles(string userId, string orgId, string[] roleIdArr)
        {
            using (TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Required))
            {
                IDictionary<string, object> param = new Dictionary<string, object> { { "UserId", userId }, { "OrgId", orgId } };
                foreach (string roleId in roleIdArr)
                {
                    param["RoleId"] = roleId;
                    dao.ExecuteNonQuery("role.insertUserRole", param);
                }
                transactionScope.Complete();
            }
        }

        #region 扩展
        /// <summary>
        /// 获取某个角色下的所有用户信息。
        /// </summary>
        /// <param name="roleID"></param>
        /// <returns></returns>
        public IList<UserInfo> GetUsersByRoleID(string roleID)
        {
            return dao.QueryEntities<UserInfo>("user.getusersbyroleid", new { RoleID = roleID });
        }
        #endregion
    }
}